package com.prs.crm.service.sys.impl;

import java.util.Collection;

import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.context.Constrains;
import com.prs.crm.dao.sys.FormDao;
import com.prs.crm.domain.sys.Form;
import com.prs.crm.domain.sys.FormField;
import com.prs.crm.service.impl.BaseServiceImpl;
import com.prs.crm.service.sys.FormService;

public class FormServiceImpl extends BaseServiceImpl<Form,FormDao> implements FormService{
	
	public  PaginationSupport listFormFields(Form form,PaginationSupport page)
	{
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(FormField.class);
		criteria.add(Restrictions.eq("form", form));
		return super.listByPage(criteria, page);
	}
	
	public Collection<Form> getAllForm()
	{
		return this.getDao().getAllForm();
	}
	
	public Form getForm(String className)
	{
		return this.getDao().findByClassName(className);
	}
	
	public  void saveField(Form form,FormField field,boolean gridshow,boolean queryfield)
	{
		int flag = 0;
		if (gridshow)flag=flag|Constrains.FORMFIELD_GRIDSHOW;
		if (queryfield)flag=flag|Constrains.FORMFIELD_QUERYFIELD;
		field.setFlag(flag);
		field.setForm(form);
		if (field.getSequence()==null)
		{
			field.setSequence(this.getDao().getMaxSequence(form)+1);
		}
		if ( !form.getFields().contains(field))
		{
			form.getFields().add(field);
		}
		super.save(form);
	}
	
	public 	void removeFiled(Form form,FormField field)
	{
		if (form.getFields().contains(field))
		{
			form.getFields().remove(field);
			adjustSequence(form);
		}
	}
	
	private void adjustSequence(Form form)
	{
		int sequence = 0;
		for (FormField field : form.getFields())
		{
			field.setSequence(++sequence);
		}
		super.save(form);
	}

	@Override
	public Form findByEname(String ename) {
		return this.getDao().findByEname(ename);
	}
}
